from flask import Flask, request, jsonify
import jwt
import datetime
from functools import wraps

# 初始化 Flask 应用
app = Flask(__name__)

# 密钥（生产环境请使用环境变量）
SECRET_KEY = "your-secret-key-here"  # ⚠️ 请务必替换成强随机字符串！

# 模拟用户数据库（实际项目应连接真实数据库）
# 现在支持多个用户，格式：{username: {password: password, user_id: user_id}}
users_db = {
    "test1": {"password": "123456", "user_id": 1001},
    "test2": {"password": "abcdef", "user_id": 1002},
    "test3": {"password": "qwerty", "user_id": 1003},
    "test4": {"password": "password123", "user_id": 1004},
    "test5": {"password": "mypassword", "user_id": 1005}
}


# =====================================
# 身份认证装饰器：验证 JWT Token
# =====================================
def token_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                "code": 401,
                "message": "Unauthorized: Missing Authorization header",
                "data": {}
            }), 401

        # 支持 "Bearer <token>" 格式
        if not auth_header.startswith("Bearer "):
            return jsonify({
                "code": 401,
                "message": "Invalid token format. Use 'Bearer <token>'",
                "data": {}
            }), 401

        token = auth_header[7:]  # 去掉 "Bearer " 前缀

        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        except jwt.ExpiredSignatureError:
            return jsonify({
                "code": 401,
                "message": "Token expired",
                "data": {}
            }), 401
        except jwt.InvalidTokenError:
            return jsonify({
                "code": 401,
                "message": "Invalid token",
                "data": {}
            }), 401

        # 将 payload 传递给被装饰的函数（可选）
        return f(payload, *args, **kwargs)

    return decorated_function


# =====================================
# 接口 1：用户登录（POST /api/login）
# =====================================
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()

    # 参数校验
    if not data or 'username' not in data or 'password' not in data:
        return jsonify({
            "code": 400,
            "message": "Bad Request: username and password are required",
            "data": {}
        }), 400

    username = data['username']
    password = data['password']

    # 验证凭据
    if username not in users_db or users_db[username]["password"] != password:
        return jsonify({
            "code": 401,
            "message": "Invalid credentials",
            "data": {}
        }), 401

    # 生成 JWT Token（有效期 30 分钟）
    payload = {
        "user_id": users_db[username]["user_id"],
        "username": username,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
        "iat": datetime.datetime.utcnow()
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")

    return jsonify({
        "code": 200,
        "message": "success",
        "data": {
            "token": token,
            "userId": users_db[username]["user_id"]
        }
    })


# =====================================
# 接口 2：获取用户资料（GET /api/user/profile）
# =====================================
@app.route('/api/user/profile', methods=['GET'])
@token_required
def get_user_profile(payload):
    print("用户信息：", payload)
    print("信息请求头：", request.headers)
    user_info = {
        "id": payload["user_id"],
        "username": payload["username"],
        "email": f"{payload['username']}@example.com",
        "nickname": f"用户{payload['username']}"
    }
    return jsonify({
        "code": 200,
        "message": "success",
        "data": user_info
    })


# =====================================
# 接口 3：查询订单（POST /api/orders）
# =====================================
@app.route('/api/orders', methods=['POST'])
@token_required
def get_orders(payload):
    # 模拟订单数据
    orders = [
        {"orderId": "ORD001", "amount": 99.9, "status": "paid"},
        {"orderId": "ORD002", "amount": 199.0, "status": "pending"}
    ]
    return jsonify({
        "code": 200,
        "message": "success",
        "data": {
            "orders": orders,
            "total": len(orders)
        }
    })


# =====================================
# 主程序入口
# =====================================
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=4999, debug=True)
